﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Windows.Forms;
using System.Configuration;
using System.Net;


namespace ElectronicJournal.Admin
{
    public partial class Banner : System.Web.UI.Page
    {
        int nFileLenUse = 47483647;

        List<String> listValidImage;
        protected void Page_Load(object sender, EventArgs e)
        {
            listValidImage = getListValidImage();

            for (int i = 0; i < listValidImage.Count; i++)
            {
                ddlChooseValidImage.Items.Add(listValidImage[i]);
            }
        }
        private List<String> getListValidImage()
        {
            try
            {
                List<String> listImage = new List<String>();
                SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);
                cnn.Open();
                SqlDataAdapter da = new SqlDataAdapter("select banner.name from  banner", cnn);

                DataTable dt = new DataTable();
                da.Fill(dt);
                if (dt.Rows.Count > 0)
                {

                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        listImage.Add(dt.Rows[i][0].ToString());
                    }
                }
                return listImage;
            }
            catch
            {
                return (new List<String>());
            }
        }
        private byte[] browseImageLocal(System.Web.UI.HtmlControls.HtmlInputFile myHtmlFile, int nFileLen)
        //private  browseImage(System.Web.UI.HtmlControls.HtmlInputFile myHtmlFile)
        {
            byte[] myData = new byte[nFileLen];
            if (myHtmlFile.PostedFile != null)
            {
                // File was sent
                // Get a reference to PostedFile object

                HttpPostedFile myFile = myHtmlFile.PostedFile;

                // Get size of uploaded file

                nFileLen = myFile.ContentLength;

                // Allocate a buffer for reading of the file



                // Read uploaded file from the Stream
                try
                {
                    myFile.InputStream.Read(myData, 0, nFileLen);
                }
                catch
                {
                }

            }
            else
            {
                // No file

            }
            return myData;
        }

        private byte[] browseImageUrl(string url)
        //private  browseImage(System.Web.UI.HtmlControls.HtmlInputFile myHtmlFile)
        {

            var webClient = new WebClient();
            byte[] myData = webClient.DownloadData(txtUrl.Text);
            return myData;
        }

        // Writes file to the database

        private void insertBannerIntoDB(string strName, byte[] Buffer, string position)
        {
            try
            {
                int fileID;

                SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);
                cnn.Open();

                SqlCommand nonqueryCommand = new SqlCommand("UPDATE banner SET position='' WHERE position=@pos", cnn);
                nonqueryCommand.Parameters.AddWithValue("@pos", position);
                nonqueryCommand.ExecuteNonQuery();

                SqlDataAdapter da = new SqlDataAdapter("select banner.idFile from  banner", cnn);

                DataTable dt = new DataTable();
                da.Fill(dt);
                if (dt.Rows.Count > 0)
                {
                    fileID = Convert.ToInt16(dt.Rows[dt.Rows.Count - 1][0].ToString()) + 1;
                }
                else
                    fileID = 1;

                SqlCommand nonqueryCommand1 = new SqlCommand("INSERT INTO banner VALUES (@id, @name, @size,@content,@postion)", cnn);
                nonqueryCommand1.Parameters.AddWithValue("@id", fileID);
                nonqueryCommand1.Parameters.AddWithValue("@name", strName);

                nonqueryCommand1.Parameters.AddWithValue("@size", Buffer.Length);
                nonqueryCommand1.Parameters.AddWithValue("@content", Buffer);
                nonqueryCommand1.Parameters.AddWithValue("@postion", position);
                nonqueryCommand1.ExecuteNonQuery();
            }
            catch
            {
            }

        }

        private void updateBannerInDB(int index, string position)
        {
            try
            {
                int fileID;
                SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);
                cnn.Open();

                SqlCommand nonqueryCommand = new SqlCommand("UPDATE banner SET position='' WHERE position=@pos", cnn);
                nonqueryCommand.Parameters.AddWithValue("@pos", position);
                nonqueryCommand.ExecuteNonQuery();

                SqlDataAdapter da = new SqlDataAdapter("select banner.idFile from  banner", cnn);

                DataTable dt = new DataTable();
                da.Fill(dt);
                if (dt.Rows.Count >= index + 1)
                {
                    fileID = Convert.ToInt16(dt.Rows[index][0].ToString());
                    SqlCommand nonqueryCommand1 = new SqlCommand("UPDATE banner SET position=@pos WHERE idFile=@id", cnn);
                    nonqueryCommand1.Parameters.AddWithValue("@pos", position);
                    nonqueryCommand1.Parameters.AddWithValue("@id", fileID);
                    nonqueryCommand1.ExecuteNonQuery();
                }



            }
            catch
            {
            }

        }


        void setBannerByLoadFileLocal(string position, string fileName)
        {
            byte[] myDataUse = browseImageLocal(filMyFile, nFileLenUse);
            insertBannerIntoDB(fileName, myDataUse, position);
        }
        void setBannerByLoadFileUrl(string position, string fileName)
        {
            byte[] myDataUse = browseImageUrl(txtUrl.Text);
            insertBannerIntoDB(fileName, myDataUse, position);
        }
        void setBannerByValidFile(int index, string position)
        {
            updateBannerInDB(index, position);
        }
        protected void btnOK_Click(object sender, EventArgs e)
        {
            //setBanner;
            if (ddlChooseValidImage.SelectedItem.Text == "Загрузить файл")
            {

                string fileName = txtFileName.Text;

                if (fileName == "")
                    lblError.Visible = true;

                else
                {
                    if (txtUrl.Text == "")
                    {
                        setBannerByLoadFileLocal(ddlPos.SelectedItem.Text, fileName);
                    }
                    else
                    {
                        setBannerByLoadFileUrl(ddlPos.SelectedItem.Text, fileName);
                        txtUrl.Text = "";
                    }
                    lblError.Visible = false;
                }
            }
            else
            {
                setBannerByValidFile(ddlChooseValidImage.SelectedIndex - 1, ddlPos.SelectedItem.Text);
            }

        }

       

    }
}